import React, { ReactElement, useState, useEffect } from 'react'
import { Checkbox } from 'antd'
import _ from 'lodash'
import style from './Index.module.less'

interface BlockProps {
  options: string[]
  value: string[]
  name: string
  detail: boolean
  onChange: (v: string[]) => void
}

// 改变选中项
function toggleValues (checked: boolean, options: string[], value: string[], onChange: (v: string[]) => void): void {
  const pureList = value.filter(li => !options.includes(li))
  if (checked) {
    onChange(pureList)
  } else {
    onChange(_.concat([], pureList, options))
  }
}

// 切换选中状态
function toggleChecked (value: string[], name: string, onChange: (v: string[]) => void): void {
  const list = [...value]
  const index = list.indexOf(name)
  if (index !== -1) {
    list.splice(index, 1)
  } else {
    list.push(name)
  }
  onChange(list)
}

function Block ({ options, value, name, detail, onChange }: BlockProps): ReactElement {
  const [checked, setChecked] = useState(false)
  const [indeterminate, setIndeterminate] = useState(false)
  useEffect(() => {
    const every = options.every(li => value.includes(li))
    const some = options.some(li => value.includes(li))
    setChecked(every)
    setIndeterminate(some && !every)
  }, [value])
  if (!detail) {
    return <Checkbox checked={checked} indeterminate={indeterminate} onChange={() => toggleValues(checked, options, value, onChange)}>{name}</Checkbox>
  }
  return (
    <>
      {
        options.map(li => {
          return <Checkbox key={li} value={li} checked={checked || value.includes(li)} onChange={() => toggleChecked(value, li, onChange)}>{li}</Checkbox>
        })
      }
    </>
  )
}

export interface AreaOption {
  本地: string[]
  外籍: string[]
  外地: string[]
}

interface Props {
  options: AreaOption
  value?: string[]
  onChange?: (v: string[]) => void
}

function Main ({ options, value = [], onChange = () => {} }: Props): ReactElement {
  const [detail, setDetail] = useState(false)
  const [checked, setChecked] = useState(false)
  const [indeterminate, setIndeterminate] = useState(false)
  useEffect(() => {
    const list = _.concat([], options.外地, options.外籍, options.外地)
    const every = list.every(li => value.includes(li))
    const some = list.some(li => value.includes(li))
    setChecked(every)
    setIndeterminate(some && !every)
  }, [value])
  return (
    <div className={style.container}>
      <Checkbox checked={checked} indeterminate={indeterminate} onClick={() => onChange(checked ? [] : _.concat([], options.外地, options.外籍, options.外地))}>全选</Checkbox>
      <Block options={options['本地']} value={value} name='本地' detail onChange={onChange} />
      <Block options={options['外地']} value={value} name='外地' detail={detail} onChange={onChange} />
      <Block options={options['外籍']} value={value} name='外籍' detail={detail} onChange={onChange} />
      <a className={style.btn} onClick={() => setDetail(!detail)}>{detail ? '收起' : '更多'}</a>
    </div>
  )
}

export default Main
